<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Services\Admin\PermissionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class PermissionController extends Controller
{
    /**
     * 列表数据
     */
    public function index(Request $request, PermissionService $permissionService): JsonResponse
    {
        return success(data: $permissionService->index());
    }

    /**
     * 查看详情
     */
    public function show(int $id, PermissionService $permissionService): JsonResponse
    {
        return success();
    }

    /**
     * 更新
     */
    public function update(Request $request, PermissionService $permissionService): JsonResponse
    {
        return success();
    }

    public function reloadPermission(PermissionService $permissionService): JsonResponse
    {
        $routes = [];
        foreach (Route::getRoutes()->getRoutes() as $route) {
            $middleware = $route->getAction('middleware') ?? [];
            if (!in_array('admin-api', $middleware)) {
                continue;
            }
            if (str_contains($route->getAction('controller'), 'App\Http\Controllers')) {
                $methods = $route->methods[0];
                $uri = $route->uri;
                $slug = md5($methods . $uri);
                $routes[$slug] = compact('methods', 'uri', 'slug');
            }
        }
        if (count($routes) !== 0) $permissionService->checkAndReload($routes);
        return success();
    }
}
